package com.eunion.web.common.base;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.data.jpa.domain.Specification;

import com.eunion.boot.security.SpringSecurityUtil;
import com.eunion.common.util.CommUtils;
import com.eunion.core.LogUtil;

/**
 * 基类的实现，提供一些基础方法. <br> 主要为子类提供通用的方法处理
 * @param <T>
 * @param <ID>
 * @version 2015-9-13
 */
public abstract class BaseTableCommonController<T, ID extends Serializable> extends BaseCommonController<T, ID> {
	
    /**
     * 判断是数字包括小数
     * @param str
     * @return
     */
    protected static boolean isNumber(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (Exception e) {}
        try {
            Double.parseDouble(str);
            return true;
        } catch (Exception e) {}
        return false;
    }
    
    /**
     * 获取user session. 如果获取失败，返回null
     */
    protected String getSessionUserName() {
        try {
            return SpringSecurityUtil.getCurrentUserName();
            // return ((SessionUser) httpSession.getAttribute(Web.SESSION_USER)).getSessionUserName();
        } catch (IllegalStateException e) {
            LOG.warn("session already invalidated {}", e.toString());
        }
        return null;
    }

    protected boolean importUpdate(List<T> list) {
    	boolean ret = false;
    	List<T> toSave = new ArrayList<>();
		List<T> toUpdate = new ArrayList<>();
        if(getBaseService().count() > 0) {
        	for(T element : list) {
            	List<T> find = getBaseService().findAll(getSpecification(element));
            	if(CommUtils.isEmpty(find)) {
            		toSave.add(element);
            	} else {
            		if(find.size() == 1) {
            			update(find.get(0),element);
            			toUpdate.add(element);
            		} else {
            			getBaseService().delete(find);
            			toSave.add(element);
            		}
            	}
            }
        }
        toSave.addAll(list);
        for(T update : toUpdate) {
        	getBaseService().saveAndFlush(update);
        }
        List<T> resultList = getBaseService().save(toSave);
        if (!CommUtils.isEmpty(toSave) && (null == resultList || resultList.size() < 1)) {
            LogUtil.get(this.getClass()).error("save scoreRankList failed");
            ret = false;
            //setModuleStatusOK(model, "导入失败");
        } else {
        	ret = true;
            //setModuleStatusOK(model, "导入成功");
        }
    	return ret;
    }
    
    protected void update(T fromDB,T fromFile) {
    }
    
    protected Specification<T> getSpecification(T t){
    	return null;
    }
}
